const express = require("express");
//集合
const AdminModule = require("../mongoose/module/index");

//引入解析token函数
const { tokenDeCode } = require("../JWT/index");
const { response } = require("express");
//截取请求头 查询token  解析token获得adminName 在数据库里查询 查询成功放行
//暴露中间件
module.exports = async (request, respons, next) => {
  const { token } = request.headers;
  const adminName = tokenDeCode(token);
  //拿用户名在数据库中查找
  try {
    const adminRe = await AdminModule.findOne({
      adminName: adminName.username,
      status: 1,
    });
    // 用户不存在;
    if (!adminRe) {
      return respons.send({
        code: 201,
        message: "权限不足",
        data: null,
      });
    }
    next();
  } catch (error) {
    //发生意外的错误
    response.send({
      code: 204,
      message: "发生意料之外的错误",
      data: null,
    });
  }
};
